#include"client_network.h"
#include<QJsonDocument>
#include <QJsonArray>
#include<QDebug>
#include"message_util.h"
ClientNetwork::ClientNetwork(QObject *parent):QObject(parent){
    socket=new QTcpSocket(this);
    bufferMap[socket] = QByteArray();
    connect(socket, &QTcpSocket::readyRead, [this]() {
        QByteArray data =this-> socket->readAll();
        bufferMap[socket].append(data); // 将数据添加到缓冲区

        // 根据换行符分割消息
        while (bufferMap[socket].contains('\n')) {
            int index = bufferMap[socket].indexOf('\n');
            QByteArray completeMessage = bufferMap[socket].left(index);
            bufferMap[socket] = bufferMap[socket].mid(index + 1);

            if (!completeMessage.isEmpty()) {
                emit rawDataReceived(socket, completeMessage); // 发出完整消息的信号
            }
        }
    });

    connect(this,&ClientNetwork::rawDataReceived,this,&ClientNetwork::onReadyRead);
}

ClientNetwork::~ClientNetwork(){
    socket->close();
}

void ClientNetwork::connectToServer(const QString &host,quint16 port){
    socket->connectToHost(host,port);
    if (socket->waitForConnected()) {
        // 连接成功，输出调试信息
        qDebug() << "Connected to server!";
    } else {
        // 连接失败，输出调试信息
        qDebug() << "Could not connect to server!";
    }
}

void ClientNetwork::sendMessage(const QByteArray &data){
    if (socket->isOpen() && socket->state() == QAbstractSocket::ConnectedState) {
        socket->write(data);
        socket->flush();
        qDebug() << "Data sent to client:" << data.left(50); // 打印前50字节
    } else {
        qDebug() << "Failed to send data: socket is not connected";
    }
}

// 处理套接字有数据可读的槽函数实现
void ClientNetwork::onReadyRead(QTcpSocket *socket, const QByteArray &data) {
    qDebug() << "get JSON message";
    // 从套接字读取所有可用的数据
    qDebug()<<data.left(500);
    if (!data.isEmpty()) {
        MessageType outType;
        QJsonObject outData;
        MessageUtil message;
        message.deserialize(data,outType,outData);
        // 根据消息类型进行不同处理
        switch (outType) {
        case LOGIN_RESPONSE: {
            qDebug() << "Login response received";
            // 发射专门用于登录响应的信号
            emit loginResponseReceived(outData);
            break;
        }
        case REGISTER_RESPONSE: {
            qDebug() << "Register response received";
            // 可以添加注册响应处理
            emit registerResponseReceived(outData);
            break;
        }
        case PRIVATE_CHAT: {
            qDebug() << "Private chat message received";
            // 处理私聊消息
            emit privateMessageReceived(outData);
            break;
        }
        case GROUP_CHAT: {
            qDebug() << "Group chat message received";
            // 处理群聊消息
            emit groupMessageReceived(outData);
            break;
        }
        case ONLINE_USERS_UPDATE: {  // 假设这是服务端发送在线用户列表的消息类型
            if (outData.contains("allUser") && outData["allUser"].isArray()) {
                emit onlineUsersUpdated(outData["allUser"].toArray());
            }
            break;
        }
        case IMAGE_TRANSFER: {
            emit imageTransferReceived(outData);
            break;
        }
        case FILE_TRANSFER: {
            emit fileTransferReceived(outData);
            break;
        }
        default: {
            qDebug() << "Unknown message type received:" << outType;
            // 仍然发射通用消息信号
            emit newMessageReceived(data);
            break;
        }
    }

    qDebug()<<"return "<<outData["remsg"]<<outData["success"]<<outData["userId"];
    } else {
        //解析失败，输出调试信息
        qDebug() << "Failed to parse JSON message";
    }
}
